package juc.utils.locks;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.StampedLock;
import java.util.stream.Collectors;

public class StampedLockExample1 {
    /**
     * ReentrantLock VS Synchronized
     * <p>
     * ReentrantReadWriteLock
     * R W X
     * W W X
     * W R X
     * R R O
     * 100 threads
     * 99 threads need read lock
     * 1 threads need write lock 容易写饥饿，写抢不到
     * 访问很快，更新很慢
     *
     * @param args
     */

    private final static StampedLock lock = new StampedLock();
    private final static List<Long> data = new ArrayList<>();

    public static void main(String[] args) {
        final ExecutorService executorService = Executors.newFixedThreadPool(10);
        Runnable readTask = () -> {
            for (; ; ) {
                read();
            }
        };
        Runnable writeTask = () -> {
            for (; ; ) {
                write();
            }
        };
        executorService.submit(readTask);
        //executorService.submit(readTask);
        //executorService.submit(readTask);
        //executorService.submit(readTask);
        //executorService.submit(readTask);
        //executorService.submit(readTask);
        //executorService.submit(readTask);
        //executorService.submit(readTask);
        //executorService.submit(readTask);
        executorService.submit(writeTask);
    }

    private static void read() {
        long stamped = -1;
        try {
            stamped = lock.readLock();
            //把data拼成字符串输出出来，#号分割，前缀R-，
            Optional.of(data.stream().map(String::valueOf)
                    .collect(Collectors.joining("#", "R-", "")))
                    .ifPresent(System.out::println);
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlockRead(stamped);
        }
    }

    private static void write() {
        long stamp = -1;
        try {
            stamp = lock.writeLock();
            data.add(System.currentTimeMillis());
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlockWrite(stamp);
        }
    }
}
